package com.example.firstdemo.service;

import org.hibernate.mapping.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.stereotype.Service;

import com.example.firstdemo.converter.StudentConverter;
import com.example.firstdemo.dao.Student;
import com.example.firstdemo.dao.StudentRepository;
import com.example.firstdemo.dto.StudentDTO;

import ch.qos.logback.core.util.StringUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.transaction.Transactional;

@Service
public class StudentServiceImpl implements StudentService {
  
  @Autowired
  private StudentRepository studentRepository;
  @Override
  public StudentDTO getStudentById(long id){
    Student student = studentRepository.findById(id).orElseThrow(RuntimeException::new);
    return StudentConverter.convertStudent(student);
  }
  @Override
  public Long addNewStudent(StudentDTO studentDTO){
    // 检查邮箱是否已注册
  java.util.List<Student> existingStudents = studentRepository.findByEmail(studentDTO.getEmail());
  if (!CollectionUtils.isEmpty(existingStudents)) {
    throw new RuntimeException("邮箱 '" + studentDTO.getEmail() + "' 已被注册");
  }
    Student student=studentRepository.save(StudentConverter.convertStudent(studentDTO));
    return student.getId();
  }
  @Override
  public void deleteStudentById(long id){
    studentRepository.findById(id).orElseThrow(() -> new RuntimeException("id:"+id+"学生不存在"));
    studentRepository.deleteById(id);
  }

  @Override
  @Transactional
  public StudentDTO updateStudentById(long Id, String name,String email){
    Student studentInDB=studentRepository.findById(Id).orElseThrow(() -> new RuntimeException("id:"+Id+"学生不存在"));
    if(StringUtils.isNotEmpty(name)&&!name.equals(studentInDB.getName())){
      studentInDB.setName(name);
    }
    if(StringUtils.isNotEmpty(email)&&!email.equals(studentInDB.getEmail())){
      studentInDB.setEmail(email);
    }
    Student student = studentRepository.save(studentInDB);
    return StudentConverter.convertStudent(student);

      }
}
